package com.lh.java.basic.concurrent;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

public class TestFutureTask {
	@SuppressWarnings({ "unchecked", "rawtypes" })
	public static void main(String[] args) throws InterruptedException,
			ExecutionException {
		final ExecutorService exec = Executors.newFixedThreadPool(5);
		Callable call = new Callable() {
			public String call() throws Exception {
				Thread.sleep(1000 * 50);
				return "Other less important but longtime things.";
			}
		};
		Future task = exec.submit(call);
		// 重要的事情
		Thread.sleep(1000 * 1);
		System.out.println("Let’s do important things.");
		// 其他不重要的事情		
		String obj="haha";
		try {
			obj = (String) task.get(5,TimeUnit.SECONDS);
		} catch (TimeoutException e) {
			task.cancel(true);
			System.out.println("3秒都没有做完");
		}
		System.out.println(obj);
		// 关闭线程池
		exec.shutdown();
	}
}
